﻿using System;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Onvif.WebApi.Common
{
    public static class HttpClientExtensions
    {
        /// <summary>
        /// 格式化输出 HttpClient 的配置信息
        /// </summary>
        /// <param name="client">HttpClient 实例</param>
        /// <returns>包含 HttpClient 配置信息的格式化字符串</returns>
        public static string ToFormatString(this HttpClient client)
        {
            if (client == null)
                return "HttpClient: null";

            var sb = new StringBuilder();
            sb.AppendLine("HttpClient Configuration:");
            sb.AppendLine($"  BaseAddress: {client.BaseAddress}");
            sb.AppendLine($"  Timeout: {client.Timeout}");
            sb.AppendLine($"  MaxResponseContentBufferSize: {client.MaxResponseContentBufferSize}");

            sb.AppendLine("  DefaultRequestHeaders:");
            if (client.DefaultRequestHeaders.Count() == 0)
            {
                sb.AppendLine("    (none)");
            }
            else
            {
                foreach (var header in client.DefaultRequestHeaders)
                {
                    sb.AppendLine($"    {header.Key}: {string.Join(", ", header.Value)}");
                }
            }

            return sb.ToString();
        }

        public static async Task<string> ToFormatString(this HttpRequestMessage request, bool includeContent = true)
        {
            if (request == null)
                return "HttpRequestMessage: null";

            var sb = new StringBuilder();
            sb.AppendLine($"HTTP {request.Method} {request.RequestUri}");
            sb.AppendLine($"Version: {request.Version}");

            // 添加请求头
            sb.AppendLine("Headers:");
            foreach (var header in request.Headers)
            {
                sb.AppendLine($"  {header.Key}: {string.Join(", ", header.Value)}");
            }

            // 添加内容（如果有）
            if (request.Content != null && includeContent)
            {
                sb.AppendLine("Content:");

                // 添加内容头
                foreach (var header in request.Content.Headers)
                {
                    sb.AppendLine($"  {header.Key}: {string.Join(", ", header.Value)}");
                }

                // 尝试读取内容（注意：内容可能只能读取一次）
                try
                {
                    var content = await request.Content.ReadAsStringAsync();
                    if (!string.IsNullOrEmpty(content))
                    {
                        // 为清晰起见，缩进内容
                        var indentedContent = content.Replace("\n", "\n    ");
                        sb.AppendLine($"    {indentedContent}");
                    }
                }
                catch (Exception ex)
                {
                    sb.AppendLine($"    [无法读取内容: {ex.Message}]");
                }
            }

            return sb.ToString();
        }

        public static async Task<string> ToFormatString(this HttpResponseMessage response)
        {
            if (response == null)
            {
                throw new ArgumentNullException(nameof(response));
            }
            // 获取响应状态码
            var sb = new StringBuilder();
            sb.AppendLine("===============Http请求信息===============");
            sb.AppendLine(await response.RequestMessage.ToFormatString());
            sb.AppendLine("===============Http响应信息===============");
            sb.AppendLine($"HTTP/{response.Version.Major}.{response.Version.Minor} {(int)response.StatusCode} {response.StatusCode}");

            // 格式化响应头
            sb.AppendLine("Headers:");
            if (response.Headers != null)
            {
                foreach (var header in response.Headers)
                {
                    sb.AppendLine($"  {header.Key}: {string.Join(", ", header.Value)}");
                }
            }

            if (response.Content != null)
            {
                // 获取内容头
                if (response.Content.Headers != null)
                {
                    foreach (var header in response.Content.Headers)
                    {
                        sb.AppendLine($"  {header.Key}: {string.Join(", ", header.Value)}");
                    }
                }

                // 读取响应内容
                try
                {
                    string content = await response.Content.ReadAsStringAsync();
                    sb.AppendLine("\nContent:");
                    sb.AppendLine(content);

                    // 如果是 JSON 内容，尝试格式化 JSON
                    if (response.Content.Headers.ContentType?.MediaType?.Equals("application/json", StringComparison.OrdinalIgnoreCase) == true)
                    {
                        try
                        {
                            var options = new JsonSerializerOptions { WriteIndented = true };
                            var parsedContent = JsonDocument.Parse(content);
                            string formattedJson = JsonSerializer.Serialize(parsedContent.RootElement, options);
                            sb.AppendLine("\nFormatted JSON Content:");
                            sb.AppendLine(formattedJson);
                        }
                        catch
                        {
                            // 如果解析失败，就忽略格式化
                        }
                    }
                }
                catch (Exception ex)
                {
                    sb.AppendLine($"Error reading content: {ex.Message}");
                }
            }

            return sb.ToString();
        }
    }
}
